﻿using System;
using System.Data;
using DevExpress.XtraCharts;
using DevExpress.XtraCharts.Native;
using DevExpress.Web.ASPxGridView;
using System.Globalization;

public partial class ReportView_ReportTop : System.Web.UI.Page
{
    private static Common common = new Common();
    private static string strTimeFormat = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            this.StartDate.Value = DateTime.Now.Date.AddDays(-1).ToString();
            this.EndDate.Value = DateTime.Now.Date.ToString();
            if (Request.QueryString["time"] != null && Request.QueryString["time"].ToString() == "d")
            {
                this.StartDate.Value = DateTime.Now.Date.AddDays(-7).ToString("yyyy/MM/dd HH:mm:ss");
                this.EndDate.Value = DateTime.Now.Date.ToString("yyyy/MM/dd HH:mm:ss");
            }

            if (Request.QueryString["connstring"] != null)
            {
                this.hidConnectString.Value = Request.QueryString["connstring"].ToString();//连接字符串
                this.hidProcedure.Value = Request.QueryString["procedure"].ToString();//存储过程名称
                this.hidReportID.Value = Request.QueryString["reportid"].ToString();//报表ID
                this.hidAbscissa.Value = Request.QueryString["x"].ToString();//横坐标名称
                //this.tdPMQ.Attributes["class"] = "unvisable";
                //this.tdTop.Attributes["class"] = "unvisable";
                this.tdEquipName.Attributes["class"] = "unvisable";
                this.tdIndicators.Attributes["class"] = "unvisable";
                GetIndicators(this.hidConnectString.Value.ToString(), Convert.ToInt32(this.hidReportID.Value.ToString()), 1);
               // InitData();
            }
        }
    }
    protected void btnSelAlarm_Click(object sender, EventArgs e)
    {
        InitData();
    }
    protected void ASPxPageControl1_ActiveTabChanged(object source, DevExpress.Web.ASPxTabControl.TabControlEventArgs e)
    {
        InitData();
    }
    protected void btnXlsExport_Click(object sender, EventArgs e)
    {
        InitData();
        this.gridExport.WriteXlsToResponse();
    }

    #region 统计图操作
    void InitSeries()
    {
        DataSet ds = getDataSet();
        DataTable dt = ds.Tables[0].Copy();//将Dt复制 
        string fieldName = "IndicatorsCN";
        string x = this.hidAbscissa.Value.ToString().Trim();// "equip_name";
        string y = "IndicatorsValue";
        dt = MySQLHelper.ConvertTable(this.hidConnectString.Value.ToString().Trim(), ds.Tables[0], this.hidAbscissa.Value.ToString().Trim(), this.hidReportID.Value.ToString().Trim());
        DataTable dt1 = MySQLHelper.SelectDistinct("equip", dt, fieldName);
        DataRow[] dr;
        this.WebChartControl1.Series.Clear();//清除所有的Series
        int length = dt1.Rows.Count;
        int labelLength = 0;
        int n = 0;//记录要存储的节点的循环标记
        string equipName = "";
        for (int i = 0; i < length; i++)
        {
            equipName = dt1.Rows[i][0].ToString();
            dr = dt.Select(fieldName + "='" + equipName + "'");
            equipName = dr[0][1].ToString();
            if (!equipName.Contains("统计开始时间") && !equipName.Contains("统计结束时间"))
            {
                this.WebChartControl1.Series.Add(equipName, GetViewType());
                this.WebChartControl1.Series[equipName].Points.Clear();
                if (i == 0)
                {
                    ((XYDiagram)WebChartControl1.Diagram).AxisX.CustomLabels.Clear();
                }  
                int num = dr.Length;
                labelLength = num / 3;
                string xAxis = string.Empty;
                for (int j = 0; j < num; j++)
                {
                    try
                    {
                        try
                        {
                            xAxis = Convert.ToDateTime(dr[j][x].ToString()).ToString(strTimeFormat, DateTimeFormatInfo.InvariantInfo);
                            //if (i == 0 && labelLength > 1 && (((j == 0 || j % labelLength == 0) && (j + labelLength <= num)) || j == num - 1))
                            if (i == 0 && (j % labelLength == 0))
                            {
                                ((XYDiagram)WebChartControl1.Diagram).AxisX.CustomLabels.Add(new CustomAxisLabel(xAxis));
                                ((XYDiagram)WebChartControl1.Diagram).AxisX.CustomLabels[n++].AxisValue = xAxis;
                            }
                        }
                        catch (Exception)
                        {
                            xAxis = dr[j][x].ToString();
                            //throw;
                        }
                        this.WebChartControl1.Series[equipName].Points.Add(new SeriesPoint(xAxis, dr[j][y]));
                    }
                    catch (Exception)
                    {
                        continue;
                    }
                   
                }
            }
        }
        if (length == 0)
        {
            this.WebChartControl1.Series.Add("", GetViewType());
        }
        string u = GetUnit();
        if (u != string.Empty)
        {
            ((XYDiagram)WebChartControl1.Diagram).AxisY.Title.Text = "单位：" + u;
            ((XYDiagram)WebChartControl1.Diagram).AxisY.Title.Visible = true;
        }
        WebChartControl1.Titles[0].Text = this.hidWebChartTitle.Value.ToString();
    }
    protected void WebChartControl1_CustomCallback(object sender, DevExpress.XtraCharts.Web.CustomCallbackEventArgs e)
    {
        InitSeries();
        if (e.Parameter == "ViewType")
        {
            PerformViewTypeAction();
        }
        else if (e.Parameter == "ShowLabels")
        {
            PerformViewTypeAction();
            SetSeriesLabel();
        }
    }
    private ViewType GetViewType()
    {
        ViewType v = ViewType.Line;
        switch ((string)cbViewType.SelectedItem.Text)
        {
            case "曲线图":
                v = ViewType.Line;
                break;
            case "柱状图":
                v = ViewType.Bar;
                break;
            case "饼图":
                v = ViewType.Pie;
                break;
            case "3D饼图":
                v = ViewType.Pie3D;
                break;
        }
        return v;
    }
    void PerformViewTypeAction()
    {
        ViewType viewType = ViewType.Line;
        switch ((string)cbViewType.SelectedItem.Text)
        {
            case "曲线图":
                viewType = ViewType.Line;
                break;
            case "柱状图":
                viewType = ViewType.Bar;
                break;
            case "饼图":
                viewType = ViewType.Pie;
                break;
            case "3D饼图":
                viewType = ViewType.Pie3D;
                break;
        }
        foreach (Series series in WebChartControl1.Series)
        {
            series.ChangeView(viewType);
            byte transparency = 0;
            if (series.View is Area3DSeriesView || series.View is AreaSeriesView || series.View is SplineAreaSeriesView)
                transparency = 135;
            ITransparableView transparableView = series.View as ITransparableView;
            if (transparableView != null)
                transparableView.Transparency = transparency;
            UpdateSeries(series);
        }

        Diagram3D diagram = WebChartControl1.Diagram as Diagram3D;
        if (diagram != null)
        {
            diagram.ZoomPercent = 120;
            XYDiagram3D xyDiagram3D = diagram as XYDiagram3D;
            if (xyDiagram3D != null)
                UpdateAxes(xyDiagram3D.AxisX, xyDiagram3D.AxisY, WebChartControl1.Series[0].View);
        }
        else
        {
            XYDiagram xyDiagram = WebChartControl1.Diagram as XYDiagram;
            if (xyDiagram != null)
                UpdateAxes(xyDiagram.AxisX, xyDiagram.AxisY, WebChartControl1.Series[0].View);
        }
    }
    bool IsFullStackedView(SeriesViewBase view)
    {
        return
            view is FullStackedAreaSeriesView ||
            view is FullStackedArea3DSeriesView ||
            view is FullStackedSplineAreaSeriesView ||
            view is FullStackedSplineArea3DSeriesView;
    }
    void UpdateAxes(AxisBase axisX, AxisBase axisY, SeriesViewBase view)
    {
        axisX.DateTimeOptions.Format = DateTimeFormat.MonthAndDay;
        if (IsFullStackedView(view))
        {
            axisY.NumericOptions.Format = NumericFormat.Percent;
            axisY.NumericOptions.Precision = 0;
        }
        else
            axisY.NumericOptions.Format = NumericFormat.General;
    }
    void UpdateSeries(Series series)
    {
        if (IsFullStackedView(series.View))
        {
            series.PointOptions.ValueNumericOptions.Format = NumericFormat.Percent;
            series.PointOptions.ValueNumericOptions.Precision = 0;
        }
        else
            series.PointOptions.ValueNumericOptions.Format = NumericFormat.General;
    }
    void SetSeriesLabel()
    {
        foreach (Series series in WebChartControl1.Series)
            series.Label.Visible = checkBoxShowLabel.Checked;
    }
    #endregion

    #region 初始化界面
    /// <summary>
    /// 获取设备名称
    /// </summary>
    /// <param name="reportType">设备类型(dxt表示交换机，tbs表示基站)</param>
    /// <param name="conn">连接数据库的字符串</param>
    private void GetEquipName(string reportType, string conn)
    {
        //根据传入的参数判断报表类型是交换机还是基站
        string procedureName = string.Empty;
        switch (reportType.ToLower())
        {
            case "dxt":
                procedureName = "report_get_all_dxt";
                break;
            case "tbs":
                procedureName = "report_get_all_tbs";
                break;
            default: break;
        }
        CommandType commtype = CommandType.StoredProcedure;
        //调用函数执行存储过程
        DataSet ds = MySQLHelper.ExecuteDataset(conn, commtype, procedureName);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            int length = ds.Tables[0].Rows.Count;
            ASPxComboBoxEquipName.Items.Clear();
            ASPxComboBoxEquipName.Items.Add("全部", "");
            for (int i = 0; i < length; i++)
            {
                ASPxComboBoxEquipName.Items.Add(ds.Tables[0].Rows[i][1].ToString(), ds.Tables[0].Rows[i][0].ToString());
            }
            // tdIndicators.Attributes["class"] = "visa";//将指标下拉框设置可将
            GetIndicators(conn, Convert.ToInt32(this.hidReportID.Value.ToString()), 1);
        }
        else
        {
            ASPxComboBoxEquipName.Visible = false;//将设备下拉框设置不可见
            //tdIndicators.Attributes["class"] = "unvisable";//将指标下拉框设置不可见
        }
    }
    /// <summary>
    /// 初始化指标下拉框
    /// </summary>
    /// <param name="conn">数据库连接字符串</param>
    /// <param name="reportid">报表类型ID</param>
    /// <param name="selectIndex">下拉框选中Index</param>
    private void GetIndicators(string conn, int reportid, int selectIndex)
    {
        string title = string.Empty;
        DataSet ds = MySQLHelper.GetIndicatorsData(conn, reportid);
        if (ds != null && ds.Tables[0].Rows.Count > 0)
        {
            title = ds.Tables[0].Rows[0][1].ToString();
            InitGridView(ds);
        }
        this.hidWebChartTitle.Value = title;
        WebChartControl1.Titles[0].Text = title;
        bLabel.InnerText = title;
    }
    private void InitGridView(DataSet ds)
    {
        int length = ds.Tables[0].Rows.Count;
        GridViewDataTextColumn col1 = new GridViewDataTextColumn();
        col1.FieldName = "equip_name";
        col1.Caption = "设备名称 ";
        Grid.Columns.Add(col1);
        for (int i = 0; i < length; i++)
        {
            GridViewDataTextColumn col = new GridViewDataTextColumn();
            col.FieldName = ds.Tables[0].Rows[i]["EN_TARGET_NAME"].ToString();
            col.Caption = ds.Tables[0].Rows[i]["CN_TARGET_NAME"].ToString();
            if (ds.Tables[0].Rows[i]["DISPLAY_IN_GRAP"].ToString() == "Y")
            {
                hidUnits.Value += ds.Tables[0].Rows[i]["UNITS"].ToString() + "#";
            }
            col.Caption = ds.Tables[0].Rows[i]["CN_TARGET_NAME"].ToString();
            Grid.Columns.Add(col);
        }
    }
    #endregion

    #region 公共操作
    /// <summary>
    /// 调用存储过程
    /// <returns></returns>
    public DataSet getDataSet()
    {
        return MySQLHelper.getDataSetTop(this.hidConnectString.Value.ToString().Trim(), this.hidProcedure.Value.ToString().Trim(), this.ASPxComboBoxTop.SelectedItem.Value.ToString().Trim(), this.StartDate.Value.ToString().Trim(), this.EndDate.Value.ToString().Trim());
    }
    private void InitData()
    {
        if (ASPxPageControl1.ActiveTabIndex == 1)
        {
            this.Grid.DataSource = getDataSet();
            this.Grid.DataBind();
        }
        else
        {
            InitSeries();
            SetSeriesLabel();
        }
    }
    protected void Grid_PageIndexChanged(object sender, EventArgs e)
    {
        this.Grid.DataSource = getDataSet();
        this.Grid.DataBind();
    }
    #endregion
    private string GetUnit()
    {
        string[] s = hidUnits.Value.Trim().Split('#');
        return s[0];
    }
}
